﻿CREATE PROCEDURE [dbo].[PriceLinesInsert]
	@ContragentId [int],
	@GoodsCode [int],
	@GoodsName [varchar](150),
	@CountryName [varchar](20),
	@ManufacturerName [varchar](70),
	@Price [decimal](19, 2),
	@Qntty [int],
	@NDSTax [tinyint],
	@BatchNumber [varchar](20),
	@ReadyBefore [smalldatetime],
	@ReestrPrice [decimal](19, 2),
	@ReestrDate [smalldatetime],
	@Mandatory [bit],
	@Drastic [bit],
	@RetailPack [int],
	@ManufactureBarCode [varchar](13),
	@GNVLS [bit],
	@Note [varchar](250)
WITH EXECUTE AS CALLER
AS
BEGIN
DECLARE @GoodsId int
DECLARE @GoodsVsContragentsId int
--Если перекодировка существует, обновляем
SELECT TOP 1 @GoodsVsContragentsId =ID, @GoodsId=GoodsId  FROM [CA].[GoodsVsContragents] 
WHERE ContragentId = @ContragentId AND GoodsCode = @GoodsCode 
AND SUBSTRING(GoodsName,1,6) = SUBSTRING(@GoodsName,1,6)
--AND ( (CountryName = @CountryName) OR 
--(@CountryName Is Null AND CountryName Is Null) )
--AND ( (@ManufacturerName = ManufacturerName) OR 
--(@ManufacturerName Is Null AND ManufacturerName Is Null) )
	IF((@GoodsId IS NOT NULL) AND (@GoodsVsContragentsId IS NOT NULL))
		BEGIN
		--DELETE PR.PriceLinesParsed WHERE
	--	ContragentId = @ContragentId AND GoodsVsContragentsId = @GoodsVsContragentsId
	--	AND GoodsId = @GoodsId
		  --GoodsCode = @GoodsCode 
		--AND GoodsName = @GoodsName
		INSERT INTO [PR].[PriceLinesParsed]
		([GoodsVsContragentsId],[ContragentId],[GoodsId],[Price],[Qntty],[NDSTax],[BatchNumber]
		,[ReadyBefore],[ReestrPrice],[ReestrDate],[Note])
		 VALUES(@GoodsVsContragentsId,@ContragentId,@GoodsId,@Price,@Qntty,@NDSTax,@BatchNumber
		,@ReadyBefore,@ReestrPrice,@ReestrDate,@Note)
RETURN 1
		END
--иначе вставляем в PR.PriceLinesNOTParsed
	ELSE
		BEGIN
		INSERT INTO [PR].[PriceLinesNOTParsed]
        ([ContragentId],[GoodsCode],[GoodsName],[CountryName],[ManufacturerName]
        ,[Price],[Qntty],[NDSTax],[BatchNumber],[ReadyBefore],[ReestrPrice],[ReestrDate]
        ,[Mandatory],[Drastic],[RetailPack],[ManufactureBarCode],[GNVLS],[Note])
     VALUES
        (@ContragentId,@GoodsCode,@GoodsName,@CountryName,@ManufacturerName,@Price,@Qntty
        ,@NDSTax,@BatchNumber,@ReadyBefore,@ReestrPrice,@ReestrDate,@Mandatory
        ,@Drastic,@RetailPack,@ManufactureBarCode,@GNVLS, @Note)
RETURN 2
		END
END


